package com.reform.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reform.pojo.phase.PhaseFile;
import com.reform.mapper.PhaseFileMapper;
import com.reform.res.Result;
import com.reform.res.ResultCode;
import com.reform.service.IPhaseFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reform.utils.JSONToArrUtils;
import com.reform.utils.VerifycUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mortale
 * @since 2021-09-21
 */
@Service
public class PhaseFileServiceImpl extends ServiceImpl<PhaseFileMapper, PhaseFile> implements IPhaseFileService {

    @Autowired
    PhaseFileMapper phaseFileMapper;

    @Override
    public Result getAllPhaseFile() {
        return Result.success(ResultCode.SUCCESS, phaseFileMapper.selectList(null));
    }

    @Override
    public Result addPhaseFiles(String phaseId, String proId, String phaseFileInfo) {
        //将字符串转换为对应数组
        List<PhaseFile> phaseFiles = JSONToArrUtils.jsonToArr(phaseFileInfo, PhaseFile.class);
        if (!VerifycUtils.verifyNullOrEmptyUtils(phaseFiles)) {
            return Result.failure(ResultCode.PARAM_JSON_IS_WRONG);
        }
        //将PhaseFile对象信息补全并添加到数据库
        assert phaseFiles != null;
        int res = 0;
        for (PhaseFile phaseFile : phaseFiles) {
            phaseFile.setPtId(phaseId);
            phaseFile.setProId(proId);
            res += phaseFileMapper.insert(phaseFile);
        }
        if (res != phaseFiles.size())
            return Result.failure(ResultCode.FAILURE);
        return Result.success(ResultCode.SUCCESS);
    }

    @Override
    public Result getPhaseFileByPhaseId(String phaseId) {
        return Result.success(ResultCode.SUCCESS, phaseFileMapper.selectList(new QueryWrapper<PhaseFile>().eq("pt_id", phaseId)));
    }

    @Override
    public Result getPhaseFileByProId(String proId) {
        return Result.success(ResultCode.SUCCESS, phaseFileMapper.selectList(new QueryWrapper<PhaseFile>().eq("pro_id", proId)));
    }

    @Override
    public Result deletePhaseFile(String pfId) {
        if (phaseFileMapper.deleteById(pfId) > 0)
            return Result.success(ResultCode.SUCCESS);
        return Result.failure(ResultCode.FAILURE);
    }

    @Override
    public Result getPhaseFileById(String proId, String phaseId) {
        return Result.success(ResultCode.SUCCESS, phaseFileMapper.selectList(new QueryWrapper<PhaseFile>().eq("pro_id", proId).eq("pt_id", phaseId)));
    }

    @Override
    public Result updateStatusByPfId(String pfId, Integer status) {
        if (phaseFileMapper.updateStatusByPfId(pfId, status) > 0)
            return Result.success(ResultCode.SUCCESS);
        return Result.failure(ResultCode.FAILURE);
    }
}
